import axios from 'axios'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: 'http://127.0.0.1:8080/api',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 如果是文件下载请求，则直接返回原始响应数据
    if (response.config.isFileDownload) {
      return response
    }

    const { code, data, message } = response.data
    if (code !== 1) {
      ElMessage.error(message || '请求失败')
      return Promise.reject(new Error(message || '请求失败'))
    }
    return data
  },
  error => {
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)


export default service
